package com.hui.util.module.location;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.hui.entity.enums.AppHttpCodeEnum;
import com.hui.handler.exception.SystemException;

/**
 * 门店位置有关的工具类
 */
public class LocationUtils {
    private static final String QQ_MAP_URL = "https://apis.map.qq.com/ws/geocoder/v1/";
    private static final double EARTH_RADIUS = 6378.137D;

    public LocationUtils() {
    }

    private static double rad(double d) {
        return d * 3.141592653589793D / 180.0D;
    }

    public static double getDistance(double lat1, double lng1, double lat2, double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2.0D * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2.0D), 2.0D) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2.0D), 2.0D)));
        s *= EARTH_RADIUS;
        s = (double) Math.round(s * 10000.0D) / 10000.0D;
        return NumberUtil.round(s, 2).doubleValue();
    }

    public static GetTencentLocationVO getLocation(String addr) {
        String key = null; //TODO 地图的KEY暂时设置为null
        if (StrUtil.isBlank(key)) {
            throw new SystemException(AppHttpCodeEnum.FAIL.getCode(), "请先配置腾讯地图key");
        } else {
            String url = StrUtil.format("?address={}&key={}", new Object[]{addr, key});
            String json = HttpUtil.get("https://apis.map.qq.com/ws/geocoder/v1/" + url);
            return (GetTencentLocationVO) JSONObject.parseObject(json, GetTencentLocationVO.class);
        }
    }
}
